package com.meij.activity.user;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.view.Menu;
import android.view.MenuItem;

import com.anno.ActionBarSet;
import com.anno.ActionBarSet.WAY;
import com.meij.MJApplaction;
import com.meij.R;
import com.meij.activity.MjActivity;
import com.meij.adapter.UserCenterPagerAdapter;
import com.meij.bean.Album;
import com.meij.bean.Person;
import com.meij.fragment.PicListFragment;
import com.meij.http.Json;
import com.meij.http.MJNetCallBack;
import com.meij.http.Url;
import com.util.FileUtils;

@SuppressWarnings("deprecation")
@ActionBarSet(title = "个人主页", way = WAY.TITLE)
public class UserCenterActivity extends MjActivity implements ActionBar.TabListener {

	private UserCenterPagerAdapter adapter;
	private ViewPager mViewPager;
	public ArrayList<Album> albums = new ArrayList<Album>();
	public String id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		actionBar.setDisplayHomeAsUpEnabled(true);
		id = getIntent().getStringExtra("id");
		initView();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.usercenter, menu);
		menu.getItem(0).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_setting) {
			Intent intent = new Intent(this, SettingActivity.class);
			startActivity(intent);
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		mViewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
	}

	private void initView() {
		adapter = new UserCenterPagerAdapter(getSupportFragmentManager());
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				actionBar.setSelectedNavigationItem(position);
			}
		});
		for (int i = 0; i < adapter.getCount(); i++) {
			actionBar.addTab(actionBar.newTab().setText(adapter.getPageTitle(i)).setTabListener(this));
		}
		getData();
	}

	private void getData() {
		String url = Url.detail + "?id=" + id;
		MJNetCallBack callBack = new MJNetCallBack(this) {
			@Override
			public void onSuccess(JSONObject object) {
				super.onSuccess(object);
				Person person = Json.getPerson(object);
				MJApplaction.userInfo.setPerson(person);
				albums.clear();
				albums.addAll(Json.getAlbums(object));
				mViewPager.setAdapter(adapter);
			}
		};
		getJson(url, callBack);
	}

	// 1图库 2拍照 3完成后的返回结果
	private final int CHOICEPHOTO = 1, TAKEPHOTO = 2, PHOTORESOULT = 3;;
	private final String IMAGE_UNSPECIFIED = "image/*";
	private final String[] photos = new String[] { "图库", "拍照" };
	private File file;

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != Activity.RESULT_OK || data == null) {
			return;
		}
		Bitmap photo;
		switch (requestCode) {
		case CHOICEPHOTO:
			Uri uri = data.getData();
			try {
				ContentResolver resolver = getContentResolver();
				photo = Media.getBitmap(resolver, uri);
				zoomPic(photo);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			break;
		case TAKEPHOTO:
			photo = data.getExtras().getParcelable("data");
			zoomPic(photo);
			break;
		case PHOTORESOULT:
			photo = data.getExtras().getParcelable("data");
			FileUtils.saveBitmapToFile(photo, "/temp.jpg");
			file = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
			postPic();
			break;
		}
	}

	private void zoomPic(Bitmap photo) {
		FileUtils.saveBitmapToFile(photo, "/temp.jpg");
		File tempFile = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
		startPhotoZoom(Uri.fromFile(tempFile));
	}

	private void postPic() {
		file = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
		String url = Url.photo_upone;
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", MJApplaction.userInfo.getUserkey());
		params.put("img", file);
		MJNetCallBack callBack = new MJNetCallBack(this) {
			@Override
			public void onSuccess(JSONObject object) {
				super.onSuccess(object);
				Toast("上传成功");
				PicListFragment fragment = (PicListFragment) adapter.getItem(1);
				fragment.getData();
			}
		};
		postJson(url, params, callBack);
	}

	/***
	 * 选择图片来源
	 */
	public void setPic() {
		Builder builder = new Builder(this);
		builder.setItems(photos, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:
					choicephoto();
					break;
				case 1:
					takephoto();
					break;
				}
			}
		});
		builder.show();
	}

	/***
	 * 图库选择
	 */
	public void choicephoto() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			Intent intent = new Intent();
			intent.setType(IMAGE_UNSPECIFIED);
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(intent, CHOICEPHOTO);
		} else {
			Toast("请先插入SD卡");
		}
	}

	/***
	 * 拍照
	 */
	public void takephoto() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(intent, TAKEPHOTO);
		} else {
			Toast("请先插入SD卡");
		}
	}

	/***
	 * 裁剪图片页面
	 */
	private void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		intent.putExtra("return-data", true);
		startActivityForResult(intent, PHOTORESOULT);
	}
}
